package com.leo.stream;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * @author xuexiaolei
 * @version 2018年01月11日
 */
public class Test {
    enum Status{
        OPEN,CLOSED
    }
    static final class Task {
        private Status status;//状态
        private Integer points;//分数
        Task(Status status, Integer points){
            this.status=status;
            this.points=points;
        }

        public Status getStatus() {
            return status;
        }

        public void setStatus(Status status) {
            this.status = status;
        }

        public Integer getPoints() {
            return points;
        }

        public void setPoints(Integer points) {
            this.points = points;
        }

        @Override public String toString() {
            return String.format("[%s, %d]", status, points);
        }
    }

    public static void main(String[] args) {
        List<Task> tasks = Arrays.asList(new Task(Status.OPEN, 5), new Task(Status.OPEN, 13), new Task(Status.CLOSED, 6));

        //所有的开放的Task的点数是多少？
        int openPoints = tasks.stream().filter(task -> task.getStatus() == Status.OPEN).mapToInt(Task::getPoints).sum();
        System.out.println("OPEN points = " + openPoints);

        //Stream的另外一个价值是Stream创造性地支持并行处理
        final double totalPoints = tasks.stream().parallel().map(task -> task.getPoints()).reduce(0, Integer::sum);
        System.out.println("Total points = " + totalPoints);

        //我们需要按照某种准则来对集合中的元素进行分组
        Map<Status, List<Task>> map = tasks.stream().collect(Collectors.groupingBy(Task::getStatus));
        System.out.println(map);

        //计算整个集合中每个task分数（或权重）的平均值来结束task的例子
        List<String> result  = tasks
        .stream()
        .mapToInt(Task::getPoints)
        .asLongStream()
        .mapToDouble(points -> points / totalPoints)
        .boxed()
        .mapToLong(weight -> (long) (weight * 100))
        .mapToObj(percent -> percent + "%")
        .collect(Collectors.toList());
        System.out.println(result);

        //Stream API不仅仅处理Java集合框架。像从文本文件中逐行读取数据这样典型的I/O操作也很适合用Stream API来处理
        String filename = "D://dubbo-consumer-info.log";
        final Path path = new File(filename ).toPath();
        try{
            Stream< String > lines = Files.lines(path, StandardCharsets.UTF_8 );
            lines.onClose( () -> System.out.println("Done!") ).forEach( System.out::println );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
